import type { ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import API from "./services";
import { TYPE } from "../types";
import { useState } from "react";
import { Button, Drawer, Form, Input, Spin } from "antd";
import { apiUrl } from "../../../config/defaultSettings";

export default () => {
  const [loading, loadingSet] = useState(false);
  const [visible, visibleSet] = useState(false);
  const [record, recordSet] = useState<TYPE.ResItem>({
    id: 0, method: "", name: "", params: "", path: "",
  });

  const [formRef] = Form.useForm();

  const columns: ProColumns[] = [
    { title: "接口名称", dataIndex: "name", hideInSearch: true },
    { title: "接口路径", dataIndex: "path" },
    {
      title: "访问方法",
      dataIndex: "method",
      width: 100,
      valueEnum: { get: "GET", post: "POST" },
      renderText: (text, record: TYPE.ResItem) => (
        <Button
          size="small"
          color="primary"
          variant="filled"
          onClick={() => {
            formRef.setFieldsValue({
              payload: "",
              result: "",
              url: apiUrl + record.path,
            });
            recordSet(record);
            loadingSet(false);
            visibleSet(true);
          }}
        >
          {text}
        </Button>
      ),
    },
  ];

  const submit = () => {
    formRef.validateFields().then((formData: any) => {
      const { payload } = formData;
      const { method, path } = record;
      formRef.setFieldsValue({ result: "" });
      loadingSet(true);
      API.test(method, path, JSON.parse(payload))
        .then(data => {
          loadingSet(false);
          let result = data.toString();
          if (typeof(data) === "object")
            result = JSON.stringify(data, null, 2);
          formRef.setFieldsValue({ result });
        })
        .catch(() => loadingSet(false));
    });
  };

  const validator = (_: any, value: string) => {
    if (!value) return Promise.reject("请输入请求参数");

    try {
      JSON.parse(value);
    } catch (err) {
      return Promise.reject("请求参数必须是JSON格式");
    }

    return Promise.resolve();
  };

  const { name, method, params } = record;

  return (
    <>
      <ProTable
        headerTitle="系统资源"
        rowKey="id"
        columns={columns}
        request={API.resource}
        pagination={false}
        footer={data => "总共 " + data.length + " 条"}
      />
      <Drawer
        title={"接口测试：" + name}
        width={768}
        open={visible}
        onClose={() => visibleSet(false)}
        styles={{
          body: { paddingBottom: 0 },
          footer: { textAlign: "right" },
        }}>
        <Form form={formRef} labelCol={{ flex: "80px" }}>
          <Form.Item label="接口地址" name="url">
            <Input readOnly addonBefore={method.toUpperCase()} />
          </Form.Item>
          <Form.Item
            label="请求参数"
            name="payload"
            rules={[{ required: true, validator }]}
          >
            <Input.Search
              maxLength={255}
              placeholder={params}
              loading={loading}
              onSearch={submit}
              enterButton={(
                <div style={{color: "var(--ant-button-primary-color)"}}>测试</div>
              )}
            />
          </Form.Item>
          <Spin spinning={loading}>
            <Form.Item label="返回结果" name="result">
              <Input.TextArea
                readOnly
                style={{
                  color: "green",
                  fontFamily: "serif",
                  lineHeight: "normal",
                  height: "calc(100vh - 217px)",
                }}
              />
            </Form.Item>
          </Spin>
        </Form>
      </Drawer>
    </>
  );
};
